<?php

namespace app\common\model;

use app\common\model\recharge\Order as ModelOrder;
use app\common\model\shop\Order;
use app\common\model\voucher\Order as VoucherOrder;
use app\common\model\wash\Order as WashOrder;
use app\common\model\wash\Serviceorder;
use fast\Http;
use think\Env;
use think\Model;
use wxpay\Wxpayapi;
use wxpay\WxPayConfig;

require_once(EXTEND_PATH . "/wxpay/WxPayData.php");

/**
 * 邮箱验证码
 */
class Coreorder extends Model
{


    // 表名
    protected $name = 'core_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [];

    //生成订单编号
    static function getorderno()
    {
        $order_no = date('YmdHis') . substr(uniqid(), 6);
        return $order_no;
    }

    //根据订单获取微信支付参数
    static function payorder($order_info, $openid)
    {
        if (Env::get('app.debug') == true) {
            $order_info->fee = 0.01;
        }
        $wxmchid = config('site.mch_id');
        $wxkey = config('site.wxkey');
        $wxappid = config('site.wx_appid');
        $wxappsecret = config('site.appsecret');
        if (!$wxmchid || !$wxkey || !$wxappid || !$wxappsecret) {
            $result = array('code' => 3, 'msg' => ('微信配置不完整'));
            return $result;
        }
        $payfees = $order_info->fee;
        //为0直接支付成功
        if ($order_info->fee == 0) {
            self::notifyOK($order_info->id);
            $result = array('code' => 2, 'msg' => ('已成功支付'));
        }
        $pay_total = sprintf('%.2f', $order_info->fee) * 100;
        // 调用支付宝进行支付
        $config = array(
            'APPID' => $wxappid,
            'MCHID' => $wxmchid,
            'WXKEY' => $wxkey,
            'APPSECRET' => $wxappsecret,
            // 'ip'=>Helper_Common::get_ip(),
        );
        $data = array(
            'user_id' => $order_info->user_id,
            'payfee' => $payfees
        );
        // $payment_sn = payment::createpayment($order_info);
        $payment_sn = $order_info->order_no;

        WxPayConfig::setconfig($wxmchid, $wxkey, $wxappid, $wxappsecret);
        $body = '微信在线支付';
        $url = getRequestHost();
        $notityUrl = $url . "api/coreorder/notify";
        $trade_type = 'JSAPI';
        //$Device_info='WEB';
        //给需要提交的必须参数赋值
        $wxpay = new \wxpay\WxPayUnifiedOrder();
        //$wxpay->SetDevice_info($Device_info);
        $wxpay->SetBody($body);
        $wxpay->SetOut_trade_no($payment_sn);
        $wxpay->SetTotal_fee($pay_total);
        $wxpay->SetNotify_url($notityUrl);
        $wxpay->SetTrade_type($trade_type);
        $wxpay->SetAttach(json_encode($data));
        $wxpay->SetOpenid($openid);
        $order =  WxPayApi::unifiedOrder($wxpay, $config);
        if (empty($order['prepay_id'])) {
            if ($order['return_code'] == 'FAIL') {
                return array('code' => 1, 'msg' => $order['return_msg']);
            } else {
                return array('code' => 10000, 'msg' => $order['err_code_des'] ?? '未知错误');
            }
        }
        $order_info->prepay_id = $order['prepay_id'];
        $order_info->save();
        $arr = array();
        $arr['appId'] = $order["appid"];
        $arr['nonceStr'] = $order["nonce_str"];
        $arr['package'] = "prepay_id=" . $order['prepay_id'];
        $arr['signType'] = "MD5";
        $arr['timeStamp'] = (string)time();
        $str = self::ToUrlParams($arr);
        $jmstr = $str . "&key=" . $wxkey;
        $arr['paySign'] = strtoupper(MD5($jmstr));
        $arr['notityUrl'] = $notityUrl;
        $arr['notis'] = $data;
        return $arr;
    }
    //微信支付签名串排序
    static function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v) {
            if ($k != "sign") {
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    //支付完成回调
    static function notifyOK($id)
    {
        $coreorder = self::get($id);
        //修改支付状态
        if ($coreorder->status == 0) {
            $coreorder->status = '1';
            $coreorder->save();

            switch ($coreorder->module_mark) {

                case 'wash':
                    WashOrder::payok($coreorder->id);
                    // $uplevel_checktag = false;
                    // Order::payok($coreorder->order_id);
                    # code...
                    break;
                case 'servicewash':
                    Serviceorder::payok($coreorder->id);
                    // $uplevel_checktag = false;
                    // Order::payok($coreorder->order_id);
                    # code...
                    break;
                case 'recharge':
                    VoucherOrder::payok($coreorder->order_id);
                    // ModelOrder::payok($coreorder->order_id);
                    break;
                default:
                    # code...
                    break;
            }
        }
    }




    /**
     * 退款
     * @Author   xy
     * @DateTime 2019-08-30T15:17:05+0800
     * @param    [type]                   $order_id [description]
     * @param    [type]                   $price    [description]
     * @return   [type]                             [description]
     */
    static function refund($order, $price, $refund_no = "")
    {
        $return = array("code" => -1, "msg" => "9999");
        if (empty($price)) {
            $return['msg'] = '金额不能为空';
            return $return;
        }
        array('code' => 3, 'msg' => ('微信配置不完整'));
        $wxmchid = config('site.mch_id');
        $wxkey = config('site.wxkey');
        $wxappid = config('site.wx_appid');
        $wxappsecret = config('site.appsecret');
        if (!$wxmchid || !$wxkey || !$wxappid || !$wxappsecret) {
            $result = array('code' => 3, 'msg' => ('微信配置不完整'));
            return $result;
        }

        $user = User::where('id', $order->user_id)->find();
        if (!$user) {
            $return['msg'] = '用户不存在';
            return $return;
        }


        $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
        $pars = array();
        $pars['appid'] = $wxappid;
        $pars['mch_id'] = $wxmchid;
        $pars['nonce_str'] = get_rand_str(32, false);
        $pars['out_trade_no'] = $order->order_no; //兼容新增payment
        $pars['out_refund_no'] = $refund_no ?? ("R_" . $order->order_no);
        $pars['total_fee'] = $order->fee * 100;
        $pars['refund_fee'] = $order->fee * 100;
        $pars['op_user_id'] = $user->openid;

        ksort($pars, SORT_STRING);
        $string1 = '';

        foreach ($pars as $k => $v) {
            $string1 .= $k . '=' . $v . '&';
        }

        $string1 .= 'key=' . $wxkey;
        $pars['sign'] = strtoupper(md5($string1));
        // $xml = array2xml($pars);
        $extras = array();

//        $certfile = ROOT_PATH . '/data/apiclient_cert.pem';
//        $keyfile = ROOT_PATH . '/data/apiclient_key.pem';

        $extras['certPath'] = APP_PATH . '/certs/apiclient_cert.pem';
        $extras['keyPath'] = APP_PATH . '/certs/apiclient_key.pem';


        $arr = post_data($url, $pars, "xml", true, $extras);

        if ($arr['return_code'] == 'SUCCESS' && $arr['result_code'] == 'SUCCESS') {
            $return['code'] = 0;
            return $return;
        }

        if ($arr['return_code'] == 'SUCCESS' && $arr['result_code'] == 'FAIL' && $arr['return_msg'] == 'OK') {
            if ($arr['err_code'] == 'NOTENOUGH') {
                $return['msg'] = "账号余额不足";
                return $return;
            } else {
                $return['msg'] = $arr['err_code'] . '订单号' . $pars['out_trade_no'];
                return $return;
            }
        } else {
            if (empty($arr['err_code_des']) || $arr['return_msg'] == $arr['err_code_des']) {
                $error = $arr['return_msg'];
            } else {
                $error = $arr['return_msg'] . ' | ' . $arr['err_code_des'];
            }

            $return['msg'] = $error . '订单号' . $pars['out_trade_no'];
            return $return;
        }
    }
}
